<!-- 页面 -->
<template>
  <s-layout title="预售订单中心" >
	  <!--商品ID搜索-->
	  <uni-search-bar
			  class="ss-flex-1"
			  radius="33"
			  placeholder="请输入商品ID搜索订单或包裹"
			  cancelButton="none"
			  @confirm="onSearch($event)"
	  />
    <su-sticky bgColor="#fff">
      <su-tabs
        :list="tabMaps"
        :scrollable="true"
        @change="onTabsChange"
        :current="state.currentTab"
      ></su-tabs>
    </su-sticky>
	  <su-sticky bgColor="#fff">
		  <su-tabs
				  v-if="state.currentTab == 2"
				  :list="tabMapsStorage"
				  @change="onTabsChangeStorage"
				  :current="state.currentTabStorage"
		  ></su-tabs>
	  </su-sticky>
	  <su-sticky bgColor="#fff">
		  <su-tabs
				  v-if="state.currentTab == 3"
				  :list="tabMapsPack"
				  @change="onTabsChangePack"
				  :current="state.currentTabPack"
		  ></su-tabs>
	  </su-sticky>
	  <view class="cicon-notice"
	        v-if="state.currentTab == 5"
	        style="padding: 10px;
	          margin: 5px;
	          width: 90%;
	          background-color: #F39800;
	          border-radius: 10px; color: #FFFFFF;">
		  <text>这里是申请退款的订单（含有代切失败的/代切成功但煤炉卖家不发货的）</text>
	  </view>
	  <view class="cicon-notice"
	        v-if="state.currentTab == 2"
	        style="padding: 10px;
	          margin: 5px;
	          width: 90%;
	          background-color: #F39800;
	          border-radius: 10px; color: #FFFFFF;">
		  <text v-if="state.currentTabStorage == 0">点击订单详情，下滑可看到入库返图以及商品代切日志</text>
		  <text v-if="state.currentTabStorage == 1">商品代切中，代切成功后您将收到微信通知</text>
		  <text v-if="state.currentTabStorage == 2">商品代切失败。（注意：退款将在24小时之内受理完成，请耐心等待；超期可联系客服处理。）</text>
		  <text v-if="state.currentTabStorage == 3">商品代切成功，请等待煤炉卖家发货到我们日本仓库（商品入库后您会收到已收货的微信通知，届时点击订单详情查看岛内返图确认）</text>
		  <text v-if="state.currentTabStorage == 4">商品已入仓，点击详情查看岛内返图，您可以选择多个商品打包成一个包裹提交发货申请，或选择暂留仓库免费存储（最多存储90天超出时限未处理的订单丢失概不负责）</text>
	  </view>
	  <view class="cicon-notice"
	        v-if="state.currentTab == 3"
	        style="padding: 10px;
	          margin: 5px;
	          width: 90%;
	          background-color: #F39800;
	          border-radius: 10px; color: #FFFFFF;">
		  <text v-if="state.currentTabPack == 0">点击包裹详情下滑可看到打包图片</text>
		  <text v-if="state.currentTabPack == 1">包裹收集其他人订单中，发起人统一付运费以及其他操作</text>
		  <text v-if="state.currentTabPack == 2">我们正在加速为您审核包裹发货路线及内容，请耐心等待</text>
		  <text v-if="state.currentTabPack == 3">包裹审核失败，可能包裹内包含无法一起邮寄的内容或路线选择不当，您可以点击重新打包再次发起</text>
		  <text v-if="state.currentTabPack == 4">我们正在为您打包，请耐心等待</text>
		  <text v-if="state.currentTabPack == 5">我们正在为您的包裹计算运费请耐心等待，运费设置后您将收到微信通知</text>
		  <text v-if="state.currentTabPack == 6">包裹已完成运费计算，请您支付运费</text>
		  <text v-if="state.currentTabPack == 7">我们正在加速发出您的包裹</text>
		  <text v-if="state.currentTabPack == 8">您的包裹已发货，快递单号将会陆续更新，如已收货请点击确认收货</text>
		  <text v-if="state.currentTabPack == 9">感谢您的信任，包裹已安全抵达</text>
	  </view>
    <s-empty
      v-if="state.pagination.total === 0"
      icon="/static/order-empty.png"
      text="暂无订单"
    ></s-empty>
	  <view v-if="state.pagination.total > 0">
		  <view v-if="state.currentTab == 3">
			  <view
					  class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
					  v-for="order in state.pagination.data"
					  :key="order.id"
			  >
				  <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
					  <view class="order-no">{{ '包裹编号：' + order.orderSn }}</view>
					  <view class="order-state ss-font-26" :class="'warning-color'">
						  <text>{{getExpressStatusName(order.status) }}</text>
					  </view>
				  </view>
				  <view class="border-bottom" v-for="(item,index) in order.orderItemList" :key="item.id">
					  <s-goods-item
							  v-if="index === 0"
							  :publish-status="item.publishStatus"
							  :img="item.pic"
							  :title="`${item.productName}`"
							  :skuText="item.productId"
							  :platformType="item.platformType"
							  :price="item.salePrice"
							  :num="item.memberId"
							  :pack="1"
					  >
					  </s-goods-item>
				  </view>
				  <view class="pay-box ss-m-t-30 ss-flex ss-row-right ss-p-r-20">
					  <view class="ss-flex ss-col-center">
						  <view v-if="order.status >= 2" class="discounts-title pay-color">运费：￥{{ order.freightAmount }}</view>
						  <view v-if="order.status >= 2" class="discounts-title pay-color">应付：￥{{ order.payAmount }}</view>
						  <view v-if="order.status >= 2" class="discounts-title pay-color">重量：{{ order.freightHeight }}kg</view>
						  <view class="discounts-title pay-color">共 <text style="font-weight: bold; color: #F39800">{{calcGoodsCount(order.orderItemList)}}</text> 笔订单</view>
					  </view>
				  </view>
				  <view
						  class="order-card-footer ss-flex ss-col-center ss-p-x-20"
				  >
					  <view class="order-state ss-font-26" :class="'warning-color'">
						  <text>
							  {{ order.sendType === 0 ? '直邮-' + order.channelName : '拼邮' }}
						  </text>
					  </view>
					  <view class="ss-flex ss-col-center ml-auto">
						  <button class="apply-btn ss-reset-button" @tap.stop="onOrderDetail(order.orderId, 'pack')">
							  查看详情
						  </button>
						  <button
								  v-if="order.status === -3 && order.memberId == userInfo.id"
								  class="delete-btn ss-reset-button"
								  @tap.stop="onEndExpress(order.orderId)"
						  >
							  结束收集
						  </button>
						  <button
								  v-if="order.status === -1 && order.memberId == userInfo.id"
								  class="delete-btn ss-reset-button"
								  @tap.stop="onDelExpress(order.orderId)"
						  >
							  重新打包
						  </button>
						  <button v-if="order.status === 3 && order.memberId == userInfo.id" class="tool-btn ss-reset-button ui-BG-Main-Gradient" @tap.stop="onDeyPay({orderSn:order.deyPayId,totalAmount: order.freightAmount, expressNo: order.orderId})">
							  支付运费
						  </button>
						  <button v-if="order.status === 5 && order.memberId == userInfo.id" class="tool-btn ss-reset-button ui-BG-Main-Gradient"
						          @tap.stop="onConfirm(order.orderId)">
							  确认收货
						  </button>
					  </view>
				  </view>
			  </view>
		  </view>
		  <view v-else>
			  <view
					  class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
					  v-for="order in state.pagination.data"
					  :key="order.id"
			  >
				  <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
					  <checkbox-group
							  v-if="sheep.$helper.isRealEmpty(order.expressId) && order.procureStatus === 4 && order.aftersaleStatus === 1 && order.status === 1 && (order.sendType === -1 || sheep.$helper.isRealEmpty(order.sendType))"
							  @change="onSelectSingle(order.orderId)"
							  class="check-box ss-flex ss-col-center ss-p-l-10"
					  >
						  <label class="radio ss-flex">
							  <checkbox
									  :checked="selectOrderIds.includes(order.orderId)"
									  color="var(--ui-BG-Main)"
									  style="transform: scale(0.8)"
							  />
						  </label>
					  </checkbox-group>
					  <view class="order-no">{{ '订单号：' + order.orderSn }}</view>
					  <view class="order-state ss-font-26" style="color:  #F39800">
						  <text>{{getOrderStatusName(order.status) }}/{{getOrderCutStatusName(order.procureStatus) }}
							  <!--<text v-if="!sheep.$helper.isRealEmpty(order.sendType) && order.sendType !== -1" >
								  {{ order.sendType === 0 ? '直邮-' + order.channelName : '拼邮' }}
							  </text>-->
						  </text>
						  <text v-if="order.aftersaleStatus > 1" class="">（{{getOrderAfterSaleStatusName(order.aftersaleStatus) }}）</text>
					  </view>
				  </view>
				  <view class="border-bottom" v-for="item in order.orderItemList" :key="item.id">
					  <s-goods-item
							  :publish-status="item.publishStatus"
							  :img="item.pic"
							  :title="item.productName"
							  :skuText="item.productId"
							  :platformType="item.platformType"
							  :price="item.salePrice"
							  :jp-price="item.purchasePrice"
							  :num="item.quantity"
					  >
						  <!--            <template #tool>-->
						  <!--              <view class="ss-flex">-->
						  <!--                <button-->
						  <!--                  class="ss-reset-button apply-btn"-->
						  <!--                  v-if="item.btns.includes('aftersale')"-->
						  <!--                  @tap.stop="-->
						  <!--                    sheep.$router.go('/pages/order/aftersale/apply', {-->
						  <!--                      item: JSON.stringify(item),-->
						  <!--                    })-->
						  <!--                  "-->
						  <!--                >-->
						  <!--                  申请售后-->
						  <!--                </button>-->
						  <!--                <button-->
						  <!--                  class="ss-reset-button apply-btn"-->
						  <!--                  v-if="item.btns.includes('re_aftersale')"-->
						  <!--                  @tap.stop="-->
						  <!--                    sheep.$router.go('/pages/order/aftersale/apply', {-->
						  <!--                      item: JSON.stringify(item),-->
						  <!--                    })-->
						  <!--                  "-->
						  <!--                >-->
						  <!--                  重新售后-->
						  <!--                </button>-->

						  <!--                <button-->
						  <!--                  class="ss-reset-button apply-btn"-->
						  <!--                  v-if="item.btns.includes('aftersale_info')"-->
						  <!--                  @tap.stop="-->
						  <!--                    sheep.$router.go('/pages/order/aftersale/detail', {-->
						  <!--                      id: item.ext.aftersale_id,-->
						  <!--                    })-->
						  <!--                  "-->
						  <!--                >-->
						  <!--                  售后详情-->
						  <!--                </button>-->
						  <!--                <button-->
						  <!--                  class="ss-reset-button apply-btn"-->
						  <!--                  v-if="item.btns.includes('buy_again')"-->
						  <!--                  @tap.stop="-->
						  <!--                    sheep.$router.go('/pages/goods/index', {-->
						  <!--                      id: item.goods_id,-->
						  <!--                    })-->
						  <!--                  "-->
						  <!--                >-->
						  <!--                  再次下单-->
						  <!--                </button>-->
						  <!--              </view>-->
						  <!--            </template>-->
					  </s-goods-item>
				  </view>
				  <!--<view v-if="!sheep.$helper.isRealEmpty(order.customsCategory)" class="pay-box ss-m-t-30 ss-flex ss-row-right ss-p-r-20">
					  <view class="ss-flex ss-col-center">
						  <view class="discounts-title pay-color tag">{{ order.customsCategory }}</view>
					  </view>
				  </view>-->
				  <view class="pay-box ss-m-t-30 ss-flex ss-row-right ss-p-r-20">
					  <view class="ss-flex ss-col-center">
						  <view class="discounts-title pay-color">共{{calcGoodsCount(order.orderItemList)}}件商品， </view>
					  </view>
					  <view class="ss-flex ss-col-center">
						  <view v-if="state.enableRealTimeRate" class="discounts-title pay-color">服务费：￥{{ order.serviceAmount.toFixed(2) }}，</view>
					  </view>
					  <view class="ss-flex ss-col-center">
						  <view class="discounts-title pay-color">实付：￥{{ order.payAmount.toFixed(2) }}</view>
					  </view>
				  </view>
				  <view
						  class="order-card-footer ss-flex ss-col-center ss-p-x-20"
				  >
					  <!-- <su-popover>
							<button class="more-btn ss-reset-button" @click.stop>更多</button>
							<template #content>
								<view class="more-item-box">
									<view class="more-item ss-flex ss-col-center ss-reset-button">
										<view class="item-title">删除订单</view>
									</view>
									<view class="more-item ss-flex ss-col-center ss-reset-button">
										<view class="item-title">查看发票</view>
									</view>
									<view class="more-item ss-flex ss-col-center ss-reset-button">
										<view class="item-title">评价晒单</view>
									</view>
								</view>
							</template>
						</su-popover> -->
					  <view class="order-state ss-font-26" :class="formatOrderColor(order.status)">
						  <text v-if="sheep.$helper.isRealEmpty(order.outOrder)">{{ getSendTypeStatus(order) }}</text>
						  <view v-if="!sheep.$helper.isRealEmpty(order.outOrder)" class="order-no" style="color: #8f30a1; font-weight: bold">
							  外网订单-{{ getPlatformsText(order.orderItemList[0]) }}
						  </view>
						  <text v-if="order.aftersaleStatus > 1" class="danger-color">（{{getOrderAfterSaleStatusName(order.aftersaleStatus) }}）</text>
					  </view>
					  <view class="ss-flex ss-col-center ml-auto">
						  <button class="apply-btn ss-reset-button" v-if="order.aftersaleStatus === 1" @tap.stop="onOrderDetail(order.orderId,'order')">
							  查看详情
						  </button>
						  <!--            <button v-if="order.status === 2 && order.aftersaleStatus === 1" class="apply-btn ss-reset-button"-->
						  <!--                    @tap.stop="onExpress(order.orderId)">-->
						  <!--              查看物流-->
						  <!--            </button>-->
						  <!--<button v-if="order.status === 2 && order.aftersaleStatus === 1" class="tool-btn ss-reset-button ui-BG-Main-Gradient"-->
						  <!--        @tap.stop="onConfirm(order.orderId)">-->
							<!--  确认收货-->
						  <!--</button>-->
						  <button
								  v-show="order.outOrder != 1"
								  v-if="[1,2,3].includes(order.status) && order.aftersaleStatus === 1 && order.procureStatus === 1" class="delete-btn ss-reset-button"
								  @tap.stop="onRefund(order)">
							  申请退款
						  </button>
						  <button
								  v-show="order.outOrder != 1"
								  v-if="order.status === 0" class="apply-btn ss-reset-button" @tap.stop="onCancel(order.orderId)">
							  取消订单
						  </button>
						  <!--            &lt;!&ndash;                <button&ndash;&gt;-->
						  <!--            &lt;!&ndash;                  v-if="[0,4,5].includes(order.status)"&ndash;&gt;-->
						  <!--            &lt;!&ndash;                  class="delete-btn ss-reset-button"&ndash;&gt;-->
						  <!--            &lt;!&ndash;                  @tap.stop="onDelete(order.id)"&ndash;&gt;-->
						  <!--            &lt;!&ndash;                >&ndash;&gt;-->
						  <!--            &lt;!&ndash;                  删除订单&ndash;&gt;-->
						  <!--            &lt;!&ndash;                </button>&ndash;&gt;-->
						  <button
								  v-show="order.outOrder != 1"
								  v-if="order.status === 0 && order.totalAmount > 0" class="tool-btn ss-reset-button ui-BG-Main-Gradient" @tap.stop="onPay({orderSn:order.payId,totalAmount: order.totalAmount, rate: order.rate})">
							  继续支付
						  </button>
						  <!--<button v-if="order.freightPayStatus === 0" class="tool-btn ss-reset-button ui-BG-Main-Gradient" @tap.stop="onDeyPay({orderSn:order.deyPayId,totalAmount: order.freightAmount})">-->
						  <!--  支付运费-->
						  <!--</button>-->
						  <!--<button v-if="sheep.$helper.isRealEmpty(order.freightPayStatus) && order.status === 1 && order.aftersaleStatus === 1 && !sheep.$helper.isRealEmpty(order.mergeOrderIds)" class="tool-btn ss-reset-button ui-BG-Main-Gradient" @tap.stop="onResetOrder(order)">
								还原订单
							</button>-->
						  <button
								  v-show="order.outOrder != 1"
								  class="ss-reset-button apply-btn" v-if="order.aftersaleStatus > 1"
								  @tap.stop="sheep.$router.go('/pages/order/aftersale/detail', {id: order.orderId })">
							  售后详情
						  </button>
						  <!--<button class="ss-reset-button apply-btn" v-if="[2,5].includes(order.aftersaleStatus)"-->
						  <!--        @tap.stop="cancelRefund(order.orderId)">-->
						  <!--  取消售后-->
						  <!--</button>-->
						  <!--            <button class="ss-reset-button apply-btn" v-if="order.status === 3 && order.aftersaleStatus === 1"-->
						  <!--                    @tap.stop="sheep.$router.go('/pages/goods/index', {id: order.items[0].productId})">-->
						  <!--              再次下单-->
						  <!--            </button>-->
					  </view>
				  </view>
			  </view>
		  </view>
	  </view>

	  <!-- 底部 -->
	  <su-fixed bottom :val="48" placeholder v-if="selectOrderIds.length > 0" :isInset="false">
		  <view class="cart-footer ss-flex ss-col-center ss-row-between ss-p-x-30 border-bottom" style="background-color: #FFFFFF !important; height: 80rpx; box-shadow: 1px 1px 20px #cccccc; width: 90%; margin-left: 1%; border-radius: 20px">
			  <view class="footer-left ss-flex ss-col-center">
				  <checkbox-group @change="onSelectAll" class="check-box ss-flex ss-col-center ss-p-r-30">
					  <label class="radio ss-flex">
						  <checkbox
								  :checked="state.isAllSelected"
								  color="var(--ui-BG-Main)"
								  style="transform: scale(0.8)"
						  />
						  <view class="ss-m-l-8"> 全选 </view>
					  </label>
				  </checkbox-group>
				  <text>合计：{{ selectOrderIds.length }} 单</text>
			  </view>
			  <view class="footer-right" style="display: flex">
				  <!--<button
						  class="ss-reset-button ui-BG-Main-Gradient pay-btn ui-Shadow-Main"
						  style="padding: 5px; height: 30px;"
						  @tap="batchConfirmSendType(-3)"
				  >
					  合箱
				  </button>-->
				  <button
						  class="ss-reset-button ui-BG-Main-Gradient pay-btn ui-Shadow-Main"
						  style="padding: 5px; height: 30px;"
						  @tap="batchConfirmSendType(0)"
				  >
					  直邮
				  </button>
				  <button
						  class="ss-reset-button ui-BG-Main-Gradient pay-btn ui-Shadow-Main"
						  style="padding: 5px; height: 30px;"
						  @tap="batchConfirmSendType(1)"
				  >
					  拼邮
				  </button>
			  </view>
		  </view>
	  </su-fixed>

    <!-- 加载更多 -->
    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
  </s-layout>
</template>

<script setup>
  import { computed, reactive } from 'vue';
  import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
  import {
	  formatOrderColor,
	  getOrderStatusName,
	  getMergeStatus,
	  getOrderAfterSaleStatusName,
	  getSendTypeStatus, getPlatformsText, getExpressStatusName, getOrderCutStatusName
  } from '@/sheep/hooks/useGoods';
  import sheep from '@/sheep';
  import _, {clone} from 'lodash';

  const pagination = {
    data: [],
    page: 1,
    total: 0,
    size: 5
  };
  // 数据
  const state = reactive({
    currentTab: 0,
	  enableRealTimeRate: false,
    currentTabPack: 0,
    currentTabStorage: 0,
	  isAllSelected: false,
    pagination: {
      data: [],
      page: 1,
      total: 0,
      size: 5,
	    productId: "",
    },
    loadStatus: '',
    deleteOrderId: 0,
    error: 0,
  });

	const selectOrderIds = reactive([])

  const userInfo = computed(() => sheep.$store('user').userInfo);

  const tabMaps = [
    {
      name: '全部订单',
      value: '-1',
    },
    {
      name: '待付款订单',
      value: '0',
    },
    {
      name: '待发货订单',
      value: '1',
    },
	  {
		  name: '我的包裹',
		  value: '-3',
	  },
    {
      name: '待收货订单',
      value: '2',
    },
    {
      name: '售后订单',
      value: '-2',
    },
  ];

  const tabMapsPack = [
	  {
		  name: '全部',
		  value: '-2',
	  },
	  /*{
		  name: '收集中',
		  value: '-3',
	  },*/
	  {
		  name: '审核中',
		  value: '0',
	  },
	  {
		  name: '审批拒绝',
		  value: '-1',
	  },
	  {
		  name: '待拍摄',
		  value: '1',
	  },
	  {
		  name: '待设置运费',
		  value: '2',
	  },
	  {
		  name: '待付款',
		  value: '3',
	  },
	  {
		  name: '待发货',
		  value: '4',
	  },
	  {
		  name: '待收货',
		  value: '5',
	  },
	  {
		  name: '已完成',
		  value: '6',
	  },
  ];

  const tabMapsStorage = [
	  {
		  name: '全部',
		  value: '-1',
	  },
	  {
		  name: '代⚡切中',
		  value: '0',
	  },
	  {
		  name: '代切失败',
		  value: '1',
	  },
	  {
		  name: '代切成功/未入库',
		  value: '2',
	  },
	  {
		  name: '日本仓库收货',
		  value: '4',
	  },
  ];

  /**
   * 选择订单
   */
	function onSelectSingle(orderId) {
	  if (!selectOrderIds.includes(orderId)) {
		  selectOrderIds.push(orderId);
	  } else {
		  selectOrderIds.splice(selectOrderIds.indexOf(orderId), 1);
	  }
	  console.log(selectOrderIds)
  }

  // 切换选项卡
  function onTabsChange(e) {
	  selectOrderIds.splice(0, selectOrderIds.length)
    if (state.currentTab === e.index) return;

    state.pagination = clone(pagination);
    state.currentTab = e.index;
    state.pagination.data = []
    getOrderList();
  }

	function onSearch(e) {
		console.log(e.value)
		state.pagination.productId = e.value
		state.pagination.data = []
		state.pagination.page = 1
		getOrderList()
	}

  function onTabsChangePack(e) {
	  selectOrderIds.splice(0, selectOrderIds.length)
	  if (state.currentTabPack === e.index) return;

	  state.pagination = clone(pagination);
	  state.currentTabPack = e.index;
	  state.pagination.data = []
	  getOrderList();
  }

  function onTabsChangeStorage(e) {
	  selectOrderIds.splice(0, selectOrderIds.length)
	  if (state.currentTabStorage === e.index) return;

	  state.pagination = clone(pagination);
	  state.currentTabStorage = e.index;
	  state.pagination.data = []
	  getOrderList();
  }

  // 订单详情
  function onOrderDetail(id, mode) {
    if (mode === 'order') {
	    sheep.$router.go('/pages/order/detail', {
		    id,
	    });
    } else if (mode === 'pack') {
	    sheep.$router.go('/pages/order/express/detail', {
		    id,
	    });
    }
  }

  // 分享拼团
  function onOrderGroupon(order) {
    sheep.$router.go('/pages/activity/groupon/detail', {
      id: order.ext.groupon_id,
    });
  }

  // 查看发票
  function onOrderInvoice(invoiceId) {
    sheep.$router.go('/pages/order/invoice', {
      invoiceId,
    });
  }

  // 继续支付
  function onPay(data) {
    console.log('data',data)
    sheep.$router.go('/pages/pay/index', {
      orderSN:data.orderSn,
      totalAmount: data.totalAmount,
      orderType: 'memberConsumer',
	    rate: data.rate
    });
  }

  // 支付运费
  function onDeyPay(data) {
		// 选择优惠券
	  uni.showModal({
		  title: '优惠券选择',
		  content: '需要使用优惠券进行抵扣运费金额么',
		  success: async function (res) {
			  if (res.confirm) {
				  sheep.$router.go('/pages/order/express/confirmCouponAndScore', {
					  orderSN:data.orderSn,
					  expressNo:data.expressNo,
					  totalAmount: data.totalAmount,
					  orderType: 'memberConsumerDeyPay'
				  })
			  } else {
				  console.log('data',data)
				  sheep.$router.go('/pages/pay/index', {
					  orderSN:data.orderSn,
					  totalAmount: data.totalAmount,
					  orderType: 'memberConsumerDeyPay'
				  });
			  }
		  }
	  });
  }

  // 评价
  function onComment(orderSN) {
    sheep.$router.go('/pages/goods/comment/add', {
      orderSN,
    });
  }

  // 确认收货
  async function onConfirm(orderId) {
    uni.showModal({
      title: '提示',
      content: '请确认包裹到达后再确认收货',
      success: async function (res) {
        if (res.confirm) {
          const res = await sheep.$api.order.confirmByExpress(orderId);
          if (res) {
            sheep.$helper.toast('收货成功')
            state.pagination = clone(pagination)
            getOrderList()
          }
        }
      },
    });
  }

  // 确认合并
  async function onConfirmPackSend() {
	  if (selectOrderIds.length === 1) {
		  // 直邮确认框
		  uni.showModal({
			  title: '确定采用直邮的方式么？',
			  content: '您仅选择了一笔订单，那么我们将以直邮的方式计算运费',
			  success: async function (res) {
				  if (res.confirm) {
					  const res = await sheep.$api.order.merge(selectOrderIds);
					  if (res) {
						  selectOrderIds.splice(0, selectOrderIds.length)
						  sheep.$helper.toast('确认邮寄方式成功, 耐心等待客服计算运费')
						  state.pagination = clone(pagination)
						  getOrderList()
					  }
				  }
			  },
		  });
	  } else {
		  uni.showModal({
			  title: '邮寄方式确认',
			  content: `您确认这 ${selectOrderIds.length}笔 订单采用拼邮的方式一起发货么？\n 【注意事项】\n 1.订单确认邮寄方式后若客服还没设置运费，那么您可以还原重新确认邮寄方式，若已设置运费则无法还原 \n 2.多笔订单一起发货后，其余订单商品将会合并到第一笔订单中`,
			  success: async function (res) {
				  if (selectOrderIds.length === 0) {
					  sheep.$helper.toast('请选择订单')
					  return
				  }
				  if (res.confirm) {
					  const res = await sheep.$api.order.merge(selectOrderIds);
					  if (res) {
						  selectOrderIds.splice(0, selectOrderIds.length)
						  sheep.$helper.toast('确认邮寄方式成功, 耐心等待客服计算运费')
						  state.pagination = clone(pagination)
						  getOrderList()
					  }
				  }
			  },
		  });
	  }
  }

	function onSelectAll() {
		console.log('全选')
		if (state.isAllSelected) {
			selectOrderIds.splice(0, selectOrderIds.length)
			state.isAllSelected = false
		} else {
			state.pagination.data.forEach(order => {
				if (!(order.aftersaleStatus === 1 && order.status === 1 && (order.sendType === -1 || sheep.$helper.isRealEmpty(order.sendType)))) {
					return;
				}
				if (selectOrderIds.includes(order.orderId)) {
					return;
				}
				selectOrderIds.push(order.orderId)
			})
			state.isAllSelected = true
		}
		console.log('选择', selectOrderIds)
	}

	function batchConfirmSendType(type) {
		if (type === 0) {
			sheep.$router.go('/pages/public/faq', {
				orderIds: selectOrderIds,
				type: type
			})
		} else if (type === -3) {
			sheep.$router.go('/pages/public/merge', {
				orderIds: selectOrderIds,
				type: type
			})
		} else {
			// 确认框
			uni.showModal({
				title: `确定采用${type === 0 ? '直邮' : '拼邮'}的方式么？`,
				content: `您选择了${selectOrderIds.length}笔订单，确认邮寄方式`,
				success: async function (res) {
					if (res.confirm) {
						/*const res = await sheep.$api.order.batchConfirmSendType(selectOrderIds, type);
						if (res) {
							selectOrderIds.splice(0, selectOrderIds.length)
							sheep.$helper.toast('确认邮寄方式成功, 耐心等待客服计算运费')
							state.pagination = clone(pagination)
							getOrderList()
						}*/
						const res = await sheep.$api.order.choosePinYou({
							selectOrderIds: selectOrderIds
						});
						if (res == 0) {
							// 选择地址
							sheep.$router.go('/pages/order/express/confirm', {
								data: JSON.stringify({
									selectOrderIds: selectOrderIds,
									sendType: type
								}),
							})
						}else {
							// 选择合箱
							sheep.$router.go('/pages/public/choosePack', {
								selectOrderIds: selectOrderIds,
								sendType: type
							});
						}

						// 选择地址
						/*sheep.$router.go('/pages/order/express/confirm', {
							data: JSON.stringify({
								selectOrderIds: selectOrderIds,
								sendType: type
							}),*/
					}
				},
			});
		}
	}

  /**
   * 还原
   * @param order
   */
  function onResetOrder(order) {
	  // 确认框
	  uni.showModal({
		  title: '确定还原订单吗？',
		  content: '【注意事项】\n 1. 订单确认邮寄方式后若客服还没设置运费，那么您可以还原重新确认邮寄方式 \n 2.若已设置运费则无法还原',
		  success: async function (res) {
			  if (res.confirm) {
				  const res = await sheep.$api.order.reset(order.orderId);
				  if (res) {
					  sheep.$helper.toast('还原成功')
					  state.pagination = clone(pagination)
					  getOrderList()
				  }
			  }
		  },
	  });
  }

  // 查看物流
  async function onExpress(orderId) {
    return
    sheep.$router.go('/pages/order/express/list', {
      orderId,
    });
  }

  // 计算商品数量
  function calcGoodsCount(data){
    let sum = 0
    data.forEach(it => {
      sum ++
    })
    return sum
  }

  // 取消订单
  async function onCancel(orderId) {
    uni.showModal({
      title: '提示',
      content: '确定要取消订单吗?',
      success: async function (res) {
        if (res.confirm) {
          const idList = [orderId]
          const res = await sheep.$api.order.cancel({idList});
          if (res) {
            sheep.$helper.toast('取消成功')
            state.pagination = clone(pagination)
            getOrderList()
          }
        }
      },
    });
  }

  // 删除运费订单
  async function onDelExpress(orderId) {
	  uni.showModal({
		  title: '提示',
		  content: '确定要重新打包订单吗? 重新打包后，改包裹将被拆散重新打包',
		  success: async function (res) {
			  if (res.confirm) {
				  const res = await sheep.$api.order.deleteExpress(orderId);
				  if (res) {
					  sheep.$helper.toast('拆散成功')
					  state.pagination = clone(pagination)
					  await getOrderList()
				  }
			  }
		  },
	  });
  }

  // 结束收集运费订单
  async function onEndExpress(orderId) {
	  uni.showModal({
		  title: '提示',
		  content: '确定要结束收集么? 结束收集后，包裹将直接转审核状态，无法继续收集订单',
		  success: async function (res) {
			  if (res.confirm) {
				  const res = await sheep.$api.order.updateExpressStatus({
					  expressNo: orderId,
					  status: 0
				  });
				  if (res) {
					  sheep.$helper.toast('提交成功')
					  state.pagination = clone(pagination)
					  await getOrderList()
				  }
			  }
		  },
	  });
  }

  // 删除订单
  function onDelete(orderId) {
    uni.showModal({
      title: '提示',
      content: '确定要删除订单吗?',
      success: async function (res) {
        if (res.confirm) {
          const { error, data } = await sheep.$api.order.delete(orderId);
          if (error === 0) {
            let index = state.pagination.data.findIndex((order) => order.id === orderId);
            state.pagination.data.splice(index, 1);
          }
        }
      },
    });
  }

  // 申请退款
  async function onRefund(order) {
	  uni.setStorageSync("refundOrder", JSON.stringify(order))
    sheep.$router.go('/pages/order/aftersale/apply')
  }

  async function cancelRefund(id) {
    uni.showModal({
      title: '提示',
      content: '确定要取消售后吗?',
      success: async function (res) {
        if (res.confirm) {
          await sheep.$api.order.aftersale.cancel(id);
          sheep.$helper.toast('取消成功')
          reloadData();
        }
      },
    });
  }

  // 获取订单列表
  async function getOrderList() {
    state.loadStatus = 'loading';
	  console.log(state.currentTabPack)
    console.log('size:', state.pagination)
    let res = await sheep.$api.order.list({
      page: state.pagination.page - 1,
      size: state.pagination.size,
      status: tabMaps[state.currentTab].value,
      packStatus: tabMapsPack[state.currentTabPack].value,
	    procureStatus: tabMapsStorage[state.currentTabStorage].value,
	    productId: state.pagination.productId
    });
    const {content, totalElements, totalPages} = res;
	  console.log(res)
    content.forEach(it => {
      it.orderItemList.forEach(item => {
        let str = "默认规格";
        /*const obj = JSON.parse(item.spData);
        Object.keys(obj).forEach((key) => {
          str += key + "：" + obj[key] + " ";
        });*/
        item.spDataValue = str;
      })
    })
    state.pagination.data = _.concat(state.pagination.data, content);
    state.pagination.total = totalElements
    if (state.pagination.page < totalPages) {
      state.loadStatus = 'more';
    } else {
      state.loadStatus = 'noMore';
    }
  }

  onLoad(async (options) => {
    if (options.type) {
      state.currentTab = options.type;
	    console.log('options.type', options.type)
	    console.log('state', state)
    }
	  getOrderList();
	  let rateRes = await sheep.$api.order.channelList({ type: 'enable_realtime_rate' });
	  state.enableRealTimeRate = rateRes[0].dictValue == '1'
	  uni.showModal({
		  title: '提示',
		  content: '💡平台为自动代切，商品自付款10min后仍然是代切中，请联系客服咨询情况（附带商品链接）；注意：代切失败的退款将在24小时之内受理完成，请耐心等待；超期可联系客服处理。',
		  showCancel: false,
		  confirmText: '知道了',
		  success: async function (res) {
			  uni.getSetting({
				  withSubscriptions: true,
				  success(res) {
					  console.log('1', res.subscriptionsSetting);
					  if (!res.subscriptionsSetting.mainSwitch) {
						  uni.openSetting({ //打开设置页
							  success(res) {

							  }
						  })
					  } else {
						  uni.requestSubscribeMessage({
							  tmplIds: ['ACfaSLxO5tVKYfFa-JK0tEvUiY-62R11ikQXrM2M36M'],
							  success(res) {

							  },
							  fail(err) {

							  }
						  })
					  }
				  }
			  })
		  },
	  });
  });

  // 加载更多
  function loadmore() {
    if (state.loadStatus !== 'noMore') {
      state.pagination.page++
      getOrderList();
    }
  }

  // 上拉加载更多
  onReachBottom(() => {
    loadmore();
  });

  //下拉刷新
  onPullDownRefresh(() => {
    state.pagination = clone(pagination);
    getOrderList();
    setTimeout(function () {
      uni.stopPullDownRefresh();
    }, 800);
  });

  function reloadData(){
    state.pagination = clone(pagination)
    getOrderList()
  }
</script>

<style lang="scss" scoped>
  .score-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }
  .tool-btn {
    width: 160rpx;
    height: 55rpx;
    background: white;
    font-size: 26rpx;
    border-radius: 30rpx;
    margin-right: 10rpx;

    &:last-of-type {
      margin-right: 0;
    }
  }
  .delete-btn {
    width: 160rpx;
    height: 55rpx;
    color: #F39800;
    background: #fee;
    border-radius: 30rpx;
    font-size: 26rpx;
    margin-right: 10rpx;
    line-height: normal;
    border: 1rpx solid #F39800;

    &:last-of-type {
      margin-right: 0;
    }
  }

  .apply-btn {
    width: 160rpx;
    height: 55rpx;
    border-radius: 30rpx;
    font-size: 26rpx;
    border: 2rpx solid #dcdcdc;
    line-height: normal;
    margin-left: 10rpx;

    &:last-of-type {
      margin-right: 0;
    }
  }

  .swiper-box {
    flex: 1;

    .swiper-item {
      height: 100%;
      width: 100%;
    }
  }

  .order-list-card-box {
	  margin-top: 20rpx;
	  margin-bottom: 20rpx;
	  box-shadow: 1px 1px 10px #d7d7d7;
	  border-radius: 20rpx;
	  padding: 5rpx;

	  .tag {
		  flex-shrink: 0;
		  padding: 4rpx 10rpx;
		  font-size: 24rpx;
		  font-weight: 500;
		  border-radius: 4rpx;
		  color: #ffffff !important;
		  background: #F39800;
	  }


    .order-card-header {
      height: 80rpx;

      .order-no {
        font-size: 26rpx;
        font-weight: 500;
      }

      .order-state {
      }
    }

    .pay-box {
      .discounts-title {
        font-size: 24rpx;
        line-height: normal;
        color: #999999;
	      margin-right: 20rpx;
      }

      .discounts-money {
        font-size: 24rpx;
        line-height: normal;
        color: #999;
        font-family: OPPOSANS;
      }

      .pay-color {
        color: #333;
      }
    }

    .order-card-footer {
      height: 100rpx;

      .more-item-box {
        padding: 20rpx;

        .more-item {
          height: 60rpx;

          .title {
            font-size: 26rpx;
          }
        }
      }

      .more-btn {
        color: $dark-9;
        font-size: 24rpx;
      }

      .content {
        width: 154rpx;
        color: #333333;
        font-size: 26rpx;
        font-weight: 500;
      }
    }
  }

  :deep(.uni-tooltip-popup) {
    background: var(--ui-BG);
  }
  .warning-color {
    color: #F39800;
  }
  .danger-color {
    color: #F39800;
  }
  .success-color {
    color: #52c41a;
  }
  .info-color {
    color: #999999;
  }

  :deep() {
	  checkbox .wx-checkbox-input {
		  border-radius: 50% !important;
		  color: #ffffff !important;
	  }

	  checkbox .wx-checkbox-input.wx-checkbox-input-checked {
		  color: #fff;
		  background: var(--ui-BG-Main);
	  }

	  .wx-checkbox-input.wx-checkbox-input-checked {
		  border: none !important;
	  }

	  .uni-checkbox-input {
		  border-radius: 50% !important;
		  color: #ffffff !important;
	  }

	  .uni-checkbox-input:hover {
		  border-color: #d1d1d1 !important;
	  }
  }

  :deep(.ui-fixed) {
	  height: 72rpx;
  }

  .cart-box {
	  width: 100%;

	  .cart-header {
		  height: 70rpx;
		  background-color: #f6f6f6;
		  width: 100%;
		  position: fixed;
		  left: 0;
		  top: v-bind('sys_navBar') rpx;
		  z-index: 1000;
		  box-sizing: border-box;
	  }

	  .cart-footer {
		  height: 100rpx;
		  background-color: #fff;

		  .pay-btn {
			  display: inline-block;
			  width: 60rpx;
			  height: 70rpx;
			  font-size: 28rpx;
			  line-height: 28rpx;
			  font-weight: 500;
			  border-radius: 40rpx;
		  }
	  }

	  .cart-content {
		  margin-top: 70rpx;
		  .goods-box {
			  background-color: #fff;
		  }
	  }
  }


</style>
